package com.platform.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.constant.Constants;
import com.platform.common.constant.HttpStatus;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.page.TableDataInfo;
import com.platform.common.enums.ResultEnum;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.SecurityUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.bean.BeanUtils;
import com.platform.common.utils.uuid.SnowflakeIdWorker;
import com.platform.system.domain.dto.TenantDto;
import com.platform.system.domain.entity.chip.Tenant;
import com.platform.system.domain.vo.chip.AuditRecordsVo;
import com.platform.system.domain.vo.chip.TenantVo;
import com.platform.system.mapper.tenant.TenantMapper;
import com.platform.system.service.ISysTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Huangkai
 */
@Service
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ISysTenantService {

    @Autowired
    ISysTenantService sysTenantService;

    @Resource
    TenantMapper tenantMapper;

    @Override
    public List<Tenant> selectTenantNameListByUid(List<String> UidList) {
        LambdaQueryWrapper<Tenant> wrapper = new QueryWrapper<Tenant>().lambda();
        wrapper.in(Tenant::getUid, UidList);
        List<Tenant> tenantList = sysTenantService.list(wrapper);
        return tenantList;
    }

    @Override
    public TenantDto selectTenantByUserId(TenantVo tenantVo) {
        LambdaQueryWrapper<Tenant> wrapper = new QueryWrapper<Tenant>().lambda();
        wrapper.eq(Tenant::getUserId, tenantVo.getUserId());
        return getTenantDto(wrapper);
    }

    @Override
    public TableDataInfo selectTenantList(TenantVo tenantVo) {
        LambdaQueryWrapper<Tenant> tenantLambdaQueryWrapper = new QueryWrapper<Tenant>().lambda();
        tenantLambdaQueryWrapper.like(StringUtils.isNotEmpty(tenantVo.getName()), Tenant::getName, tenantVo.getName());
        tenantLambdaQueryWrapper.like(StringUtils.isNotEmpty(tenantVo.getCreditCode()), Tenant::getCreditCode, tenantVo.getCreditCode());
        tenantLambdaQueryWrapper.eq(tenantVo.getAuditStatus() != null, Tenant::getAuditStatus, tenantVo.getAuditStatus());
        tenantLambdaQueryWrapper.orderByDesc(Tenant::getCreateTime);
        Page<Tenant> page = new Page<>();
        page.setCurrent(tenantVo.getPageNum());
        page.setSize(tenantVo.getPageSize());
        IPage<Tenant> chipIPage = tenantMapper.selectPage(page, tenantLambdaQueryWrapper);
        TableDataInfo rspData = new TableDataInfo();
        List<TenantDto> tenantDtoList = new ArrayList<>();
        if(chipIPage.getRecords() != null && chipIPage.getRecords().size() > 0){
            String json = JSONArray.toJSONString(chipIPage.getRecords());
            tenantDtoList = JSONArray.parseArray(json, TenantDto.class);
        }
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(tenantDtoList);
        rspData.setTotal(chipIPage.getTotal());
        return rspData;
    }

    @Override
    public TenantDto selectTenant(TenantVo tenantVo) {
        LambdaQueryWrapper<Tenant> wrapper = new QueryWrapper<Tenant>().lambda();
        wrapper.eq(StringUtils.isNotEmpty(tenantVo.getUid()), Tenant::getUid, tenantVo.getUid());
        wrapper.eq(StringUtils.isNotEmpty(tenantVo.getName()), Tenant::getName, tenantVo.getName());
        return getTenantDto(wrapper);
    }

    @Override
    public AjaxResult insertTenant(TenantVo tenantVo) {
        Tenant tenant = new Tenant();
        tenant.setUserId(SecurityUtils.getUserId());
        tenant.setUid(SnowflakeIdWorker.getSnowflakeIdWorker());
        tenant.setName(tenantVo.getName());
        tenant.setCreditCode(tenantVo.getCreditCode());
        tenant.setBusinessCardUid(tenantVo.getBusinessCardUid());
        //审批中
        tenant.setAuditStatus(Constants.NUM_ZERO);
        tenant.insert();
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approveTenant(TenantVo tenantVo) {
        TenantDto tenantDto = sysTenantService.selectTenant(tenantVo);
        if(tenantDto == null){
            throw new BusinessException(ResultEnum.DATA_NOT_EXIST);
        }

        tenantDto.setAuditStatus(tenantVo.getAuditStatus());
        tenantDto.setAuditUserId(SecurityUtils.getUserId());

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        AuditRecordsVo auditRecordsVo = build(tenantDto);
        auditRecordsVo.setAuditTime(new Date());
        auditRecordsVo.setTenantUid(sysUser.getTenantUid());
        String objectStr = JSONObject.toJSONString(auditRecordsVo);

        return sysTenantService.updateTenant(tenantVo);
    }

    @Override
    public AjaxResult updateTenant(TenantVo tenantVo) {
        LambdaUpdateWrapper<Tenant> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Tenant:: getUid, tenantVo.getUid());
        Tenant tenant = new Tenant();
        BeanUtils.copyProperties(tenantVo, tenant);
        boolean flag = tenant.update(lambdaUpdateWrapper);
        if(!flag){
            throw new BusinessException(ResultEnum.DATA_NOT_EXIST);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteTenant(TenantVo tenantVo) {
        LambdaQueryWrapper<Tenant> wrapper = new QueryWrapper<Tenant>().lambda();
        wrapper.in(Tenant::getUid, tenantVo.getUidList());
        tenantMapper.delete(wrapper);
        return AjaxResult.success();
    }

    private TenantDto getTenantDto(LambdaQueryWrapper<Tenant> wrapper) {
        Tenant tenant = sysTenantService.getOne(wrapper);
        if(tenant != null){
            TenantDto tenantDto = new TenantDto();
            BeanUtils.copyProperties(tenant, tenantDto);
            return tenantDto;
        }
        return null;
    }


    public AuditRecordsVo build(TenantDto tenantDto){
        //记录审批信息
        AuditRecordsVo auditRecordsVo = new AuditRecordsVo();
        auditRecordsVo.setName(tenantDto.getName());
        auditRecordsVo.setAuditUserId(tenantDto.getAuditUserId());
        auditRecordsVo.setUserId(tenantDto.getUserId());
        auditRecordsVo.setAuditStatus(tenantDto.getAuditStatus());
        auditRecordsVo.setAuditTime(new Date());
        auditRecordsVo.setAuditType(Constants.NUM_TWO);
        auditRecordsVo.setResourceType(Constants.NUM_THREE);
        auditRecordsVo.setResourceUid(tenantDto.getUid());
        auditRecordsVo.setRejectReason(tenantDto.getRejectReason());
        return auditRecordsVo;
    }

}
